package com.s64.ch08.controller;

import com.s64.ch08.entity.AjaxResult;
import com.s64.ch08.entity.User;
import com.s64.ch08.modules.security.LoginUser;
import com.s64.ch08.modules.token.Token;
import com.s64.ch08.modules.token.TokenService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.web.bind.annotation.*;

@RestController
@RequiredArgsConstructor
@Api(value = "登录控制器")
public class LoginController {
    private final TokenService tokenService;
    private final AuthenticationManager authenticationManager;

    @ApiOperation(value = "用户登录")
    @PostMapping("/login")
    public AjaxResult login(@RequestBody User user) {
        // 将自定义User类转换成ss需要的UsernamePasswordAuthenticationToken对象
        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(user.getUserName(), user.getPassword());
        // 通过ss自动调用UserDetailsServiceImpl.loadUserByUsername方法
        Authentication authenticate = authenticationManager.authenticate(authenticationToken);
        LoginUser loginUser = (LoginUser) authenticate.getPrincipal();
        Token token = tokenService.createToken(loginUser);
        return AjaxResult.ok(token);
    }
}
